package com.hzjy.api.controller;

import com.alibaba.fastjson.JSON;
import com.hzjy.api.beans.HzjyAcceptAddress;
import com.hzjy.api.service.BqTokenService;
import com.hzjy.api.service.impl.BqUserServiceImpl;
import com.hzjy.api.service.impl.HzjyAcceptAddressServiceImpl;
import com.hzjy.api.vo.BqLoginUser;
import com.hzjy.api.vo.BqRegisterBody;
import com.hzjy.api.vo.BqUser;
import com.hzjy.common.core.controller.BaseApiController;
import com.hzjy.common.core.domain.AjaxResult;
import com.hzjy.common.core.redis.RedisCache;
import com.hzjy.common.exception.CustomException;
import com.hzjy.common.utils.JSONUtil;
import com.hzjy.common.utils.PageData;
import com.hzjy.common.utils.ServletUtils;
import com.hzjy.common.utils.StringUtils;
import com.hzjy.common.utils.sign.Md5Utils;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 个人资料修改
 *
 * @author SS
 */
@RestController
@RequestMapping("/api/personalData")
public class ApiPersonalDataController extends BaseApiController {
    private static final Logger log = LoggerFactory.getLogger(ApiMyTradingController.class);
    @Autowired
    private BqTokenService bqTokenService;

    @Autowired
    private BqUserServiceImpl bqUserService;

    @Autowired
    private HzjyAcceptAddressServiceImpl hzjyAcceptAddressService;

    @Autowired
    private RedisCache redisCache;
    @Value("${MD5.key}")
    private String key;

    /**
     * 查询个人信息
     *
     * @return
     */
    @ApiOperation("账户信息")
    @PostMapping("/findByUserId")
    public AjaxResult findByUserId() {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        BqUser bqUser = loginUser.getBqUser();
        Long userId = bqUser.getUserId();
        BqUser byUserId = bqUserService.findByUserId(userId.toString());
        return AjaxResult.success(200, "成功", byUserId);
    }

    /**
     * 修改用户信息
     *
     * @return
     */
    @ApiOperation("修改用户信息")
    @PostMapping("/updateByUserId")
    private AjaxResult updateByUserId(@RequestBody BqUser bqUser) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        Long userId = loginUser.getBqUser().getUserId();
        bqUser.setUserId(userId);
        if (StringUtils.isNotNull(bqUser.getPhone())) {
            //如果手机号不为空
            BqUser byPhone = bqUserService.findByPhone(bqUser.getPhone());
            if (!byPhone.getUserId().equals(bqUser.getUserId())) {
                return AjaxResult.error(500, "手机号已存在");
            }
        }
        bqUserService.submitEditData(bqUser);
        return AjaxResult.success();
    }


    /**
     * 查询用户收货地址
     *
     * @param hzjyAcceptAddress
     * @return
     */
    @ApiOperation("查询用户收货地址")
    @PostMapping("/findAcceptAddress")
    private AjaxResult findAcceptAddress(@RequestBody HzjyAcceptAddress hzjyAcceptAddress) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        Long userId = loginUser.getBqUser().getUserId();
        hzjyAcceptAddress.setUserId(userId);
        List<HzjyAcceptAddress> hzjyAcceptAddresses = hzjyAcceptAddressService.selectHzjyAcceptAddressList(hzjyAcceptAddress);
        return AjaxResult.success(200, "成功", hzjyAcceptAddresses);
    }

    /**
     * 修改用户收货地址
     *
     * @param hzjyAcceptAddress
     * @return
     */
    @ApiOperation("修改用户收货地址")
    @PostMapping("/updateAcceptAddress")
    private AjaxResult updateAcceptAddress(@RequestBody HzjyAcceptAddress hzjyAcceptAddress) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        Long userId = loginUser.getBqUser().getUserId();
        hzjyAcceptAddress.setUserId(userId);
        hzjyAcceptAddressService.updateHzjyAcceptAddress(hzjyAcceptAddress);
        return AjaxResult.success();
    }

    /**
     * 新增用户收货地址
     *
     * @param hzjyAcceptAddress
     * @return
     */
    @ApiOperation("新增用户收货地址")
    @PostMapping("/addAcceptAddress")
    private AjaxResult addAcceptAddress(@RequestBody HzjyAcceptAddress hzjyAcceptAddress) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        BqUser bqUser = loginUser.getBqUser();
        Long userId = bqUser.getUserId();
        hzjyAcceptAddress.setUserId(userId);
        hzjyAcceptAddressService.insertHzjyAcceptAddress(hzjyAcceptAddress);
        return AjaxResult.success();
    }

    /**
     * 删除用户收货地址
     *
     * @param hzjyAcceptAddress
     * @return
     */
    @ApiOperation("删除用户收货地址")
    @PostMapping("/deleteAcceptAddress")
    private AjaxResult deleteAcceptAddress(@RequestBody HzjyAcceptAddress hzjyAcceptAddress) {

        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        BqUser bqUser = loginUser.getBqUser();
        Long userId = bqUser.getUserId();
        hzjyAcceptAddress.setUserId(userId);
        hzjyAcceptAddressService.deleteHzjyAcceptAddressById(hzjyAcceptAddress.getAcceptAddressId());
        return AjaxResult.success();
    }

    /**
     * 设置默认收货地址
     *
     * @param hzjyAcceptAddress
     * @return
     */
    @ApiOperation("设置默认收货地址")
    @PostMapping("/defaultAcceptAddress")
    private AjaxResult defaultAcceptAddress(@RequestBody HzjyAcceptAddress hzjyAcceptAddress) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        BqUser bqUser = loginUser.getBqUser();
        Long userId = bqUser.getUserId();
        hzjyAcceptAddress.setUserId(userId);
        hzjyAcceptAddressService.defaultAcceptAddress(hzjyAcceptAddress);
        return AjaxResult.success();
    }

    /**
     * 修改密码
     *
     * @param bqRegisterBody
     * @return
     */
    @ApiOperation("修改密码")
    @PostMapping("/updatePassWord")
    private AjaxResult updatePassWord(@RequestBody BqRegisterBody bqRegisterBody) {

        //判断前端传的验证码是否为空
        if (StringUtils.isNull(bqRegisterBody.getCode())) {
            return AjaxResult.error("请填写验证码");
        }

        if (StringUtils.isNotNull(bqRegisterBody.getNewPhone())) {
            if (bqUserService.findByPhone(bqRegisterBody.getNewPhone()) != null) {
                return AjaxResult.error("该手机号已存在");
            }
            bqRegisterBody.setPhone(bqRegisterBody.getNewPhone());
        }
        //校验短信验证码
        String code = redisCache.getCacheObject(bqRegisterBody.getPhone());
        if (StringUtils.isNull(code)) {
            return AjaxResult.error("验证码已过期");
        }
        if (!StringUtils.equals(code, bqRegisterBody.getCode())) {
            return AjaxResult.error("验证码错误");
        }
        bqUserService.updatePassWord(bqRegisterBody);
        return AjaxResult.success();
    }


    /**
     * 实名认证
     *
     * @param bqUser
     * @return
     */
    @ApiOperation("实名认证")
    @PostMapping("/realNameAuthentication")
    public AjaxResult realNameAuthentication(@RequestBody BqUser bqUser) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        Long userId = loginUser.getBqUser().getUserId();
        bqUser.setUserId(userId);
        bqUserService.realNameAuthentication(bqUser);
        return AjaxResult.success("请在手机上进行实名认证");
    }

    /**
     * 实名认证返回
     *
     * @param request
     */
    @RequestMapping(value = "callBackRealName")
    public void callBackRealName(HttpServletRequest request) {
        log.info("【实名认证回调入口】");
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");
            log.info("【实名认证回调结果】:" + result);
            Map mp = JSON.parseObject(result);
            log.info("====【实名认证回调结果json】====" + JSONUtil.map2json(mp));
            Object success = mp.get("success");
            Object flowId = mp.get("flowId");
            if (flowId == null || success == null) {
                return;
            }
            Boolean flag = (Boolean) success;
            if (flag) {
                BqUser bqUser = bqUserService.findByFlowId(flowId.toString());
                bqUser.setRealNameCertification(3);//已实名认证
                bqUserService.submitEditData(bqUser);
            }
        } catch (Exception ex) {
            log.error("****************************实名认证回调*************************." + ex.getMessage());
        }
    }

    /**
     * 修改用户信息
     *
     * @return
     */
    @ApiOperation("绑定手机号和openId")
    @PostMapping("/updateByOpenId")
    private AjaxResult updateByOpenId(@RequestBody BqUser bqUser) {

        BqUser byPhone = bqUserService.findByPhone(bqUser.getPhone());
        String password = Md5Utils.hash(bqUser.getPassWord() + key);
        //System.out.println(password);
        if (byPhone != null) {
            if (!byPhone.getPassWord().equals(password)) {
                throw new CustomException("密码错误");
            }
        } else {
            throw new CustomException("该账号不存在");
        }
        byPhone.setWechatState(1);
        byPhone.setOpenId(bqUser.getOpenId());
        bqUserService.submitEditData(byPhone);
        BqLoginUser bqLoginUser = new BqLoginUser();
        bqLoginUser.setBqUser(byPhone);
        String token = bqTokenService.createToken(bqLoginUser);
        return AjaxResult.success(200, "绑定成功", token);
    }

    /**
     * 修改密码
     *
     * @param bqRegisterBody
     * @return
     */
    @ApiOperation("小程序修改密码")
    @PostMapping("/wxUpdatePassWord")
    private AjaxResult wxUpdatePassWord(@RequestBody BqRegisterBody bqRegisterBody) {
        BqLoginUser loginUser = bqTokenService.getBqLoginUser(ServletUtils.getRequest());
        if (loginUser == null) {
            return AjaxResult.error(401, "未登录");
        }
        BqUser bqUser = loginUser.getBqUser();
        Long userId = bqUser.getUserId();
        BqUser byPhone = bqUserService.findByPhone(bqRegisterBody.getPhone());
        if (byPhone != null){
            if (byPhone.getUserId() != userId){
                return AjaxResult.error("该手机号已被注册");
            }
        }else {
            if (StringUtils.isNull(bqRegisterBody.getCode())) {
                return AjaxResult.error("请填写验证码");
            }
            //校验短信验证码
            String code = redisCache.getCacheObject(bqRegisterBody.getPhone());
            if (StringUtils.isNull(code)) {
                return AjaxResult.error("验证码已过期");
            }
            if (!StringUtils.equals(code, bqRegisterBody.getCode())) {
                return AjaxResult.error("验证码错误");
            }
        }
        bqUserService.updatePassWord(bqRegisterBody);
        return AjaxResult.success();
    }
}
